package pchfserver;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * PC-文件传输工具窗口
 * 
 * @author 854185
 *
 */
public class HttpFileServerMainFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1713465740003533612L;

	/**
	 * 获取拖拽的文件的路径
	 * @return
	 */
	public String getFilePath() {
		final JTextArea jArea = new JTextArea();
		jArea.setLineWrap(true);
		add(new JScrollPane(jArea));
		new DropTarget(jArea, DnDConstants.ACTION_COPY_OR_MOVE, new DropTargetAdapter() {
			@SuppressWarnings("unchecked")
			@Override
			public void drop(DropTargetDropEvent dtde) {
				if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
					dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); // 接收拖拽进来的数据
					List<File> list;
					try {
						list = (List<File>) (dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
						jArea.setText("本地文件地址为：");
						for (File file : list) {
							jArea.append(file.getAbsolutePath());
							jArea.append("\r\n");
							setSysClipboardText(getWgetUrl(file));
						}
						dtde.dropComplete(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		setTitle("PC-文件传输工具_V2.0      版权所有,翻版必究");
		setSize(410, 300);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		return jArea.getText();
	}

	public static void main(String[] args) throws UnknownHostException {
		String filepath = new HttpFileServerMainFrame().getFilePath();
		new HttpFileServer().start(filepath);
	}
	
	/**
	 * 生成wget地址
	 * @param file
	 * @return
	 */
	private String getWgetUrl(File file){
		String uri = file.getAbsolutePath().substring(3);
		uri=uri.replace("\\", "/");
		String resultUrl = null;
		if(null!=uri && !uri.equals("")){
			String localIp;
			try {
				localIp = InetAddress.getLocalHost().getHostAddress();
				resultUrl = "wget -O "+file.getName()+" http://"+localIp+":8080/"+uri;
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		return resultUrl;
	}
	
	/** 
     * 将字符串复制到粘贴板。 
     */  
    public static void setSysClipboardText(String writeMe) {  
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();  
        Transferable tText = new StringSelection(writeMe);  
        clip.setContents(tText, null);  
    } 
}
